Yes. A class definition may have its own variables (state), and may have its own methods (behavior).
// The file StringTester.java
//
class StringTester
{
public static void main ( String[] args )
{
String str1; // str1 is a reference to an object,
int len; // len is a primitive variable of type int
str1 = new String("Random Jottings"); // create an object of type String
len = str1.length(); // invoke the object's method length()
System.out.println("The string is " + len + " characters long");
}
}
The methods that belong to a class definition are called static methods. (Sometimes they are called class methods, but this is confusing.) A static method is part of a class definition, but is not part of the objects it creates.
Important: A program can execute a static method without first creating an object! All other methods (those that are not static) exist only when they are part of an object. So an object must be created before they can be executed.
The example application is similar to many you have seen so far.
Let us look at what is going on.
Assume that the source code is in a file named StringTester.java
.
StringTester
.main()
.main()
is a static method,
it is a characteristic of the class.
Objects of the class do not have a main()
method.main()
is a static method,
there will be only one main()
method.
main()
method can be run without an object.java StringTester
(or clicking on a button in a programming environment.).
main()
method.
main()
method starts running,
creates a String
object using new
,
invokes its length()
method, and continues.
Remember the idea of object-oriented programming: an application consists of a collection of cooperating software objects whose methods are executed in a particular order to get something useful done. The steps listed above is how the collection of objects gets started. (In this case only one object was created.)
Say that you create a file that
contains the definition of a class,
but the the class contains no main()
method.
Can the methods of this class ever be executed?